import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import '@/assets/css/global.css'
import '@/assets/css/main.css'
import 'element-plus/dist/index.css'
import '@/assets/css/theme.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

createApp(App)
    .use(router)
    .use(store)
    .use(ElementPlus)
    .mount('#app')

// 自动建立SSE连接（如果用户已登录）
import { useUserStore } from '@/store/user'
import { useGenerator } from '@/hook/useGenerator'

const initializeApp = () => {
    const userStore = useUserStore()

    // 如果用户已登录，建立SSE连接
    if (userStore.isLoggedIn && userStore.userInfo.userId) {
        console.log('[App] 检测到用户已登录，建立SSE连接...')

        // 获取generator实例并建立SSE连接
        const { establishSSEConnection } = useGenerator()
        establishSSEConnection(userStore.userInfo.userId)
    }
}

// 延迟初始化以确保store已经准备好
setTimeout(initializeApp, 1000)

// 监听用户登录状态变化
import { watch } from 'vue'
const userStore = useUserStore()

watch(
    () => userStore.isLoggedIn,
    (isLoggedIn) => {
        if (isLoggedIn && userStore.userInfo.userId) {
            console.log('[App] 用户登录，建立SSE连接')
            const { establishSSEConnection } = useGenerator()
            establishSSEConnection(userStore.userInfo.userId)
        } else {
            console.log('[App] 用户登出，关闭SSE连接')
            const { closeSSEConnection } = useGenerator()
            closeSSEConnection()
        }
    },
    { immediate: false }
)
